$(function () {
    back();
    add_shop();
});

function back() {
    $('#back-button').click(() => {
        window.location.href = '/page/shoper-main.html';
    });
}

function add_shop() {
    $('#add-confirm').click(() => {
        if ($('#spare-img').val() != '' && $('#spare-name').val() != '' && $('#spare-number').val() != '' && $('#spare-price').val()) {
            $.ajax({
                url: '/add-product',
                type: 'POST',
                dataType: 'JSON',
                data: {
                    name: $('#spare-name').val(),
                    image: $('#spare-img').val().substring($('#spare-img').val().lastIndexOf('\\') + 1,),
                    price: $('#spare-price').val(),
                    num: $('#spare-number').val(),
                },
                success: function (data) {
                    if (data.status) {
                        $('#add-confirm').attr('class', 'btn btn-success');
                        $('#add-confirm').text('添加成功，正在跳转');
                        setTimeout(function () {
                            window.location.href = '/page/shoper-main.html';
                        }, 1000);
                    } else {
                        $('#add-confirm').attr('class', 'btn btn-danger');
                        $('#add-confirm').text('添加失败');
                    }
                }
            });
            
        } else {
            $('#add-confirm').attr('class', 'btn btn-danger');
            $('#add-confirm').text('请完善信息后重试');
        }
    });
}